package com.tinem.platform.web.gateway.filter;

import com.tinem.platform.module.pojo.co.GatewayHeadName;
import com.tinem.platform.module.pojo.co.JwtPropertyName;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author fengzhihao
 * @version v1
 * @program: platform
 * @className ChannelScopeGatewayFilterFactory
 * @description TODO
 * @site 
 * @company 
 * @create 2020-07-03 12:26
 */
@Component
@Slf4j
public class ClientGatewayFilterFactory  extends AbstractGatewayFilterFactory<Object> {
    @Resource
    StringRedisTemplate stringRedisTemplate;
    @Override
    public GatewayFilter apply(Object config) {
        return (exchange, chain) ->  exchange.getPrincipal()
                .cast(JwtAuthenticationToken.class)
                .flatMap(jwtAuthenticationToken -> {
                    String clientId = jwtAuthenticationToken.getToken().getClaimAsString(JwtPropertyName.CLIENT_ID);
                    exchange.getAttributes().put(GatewayHeadName.X_PLATFORM_GATEWAY_CONTEXT_CLIENT_ID,clientId);
                    return chain.filter(exchange);
                });
    }
}
